﻿using System.ComponentModel;
using Dyao.Book.Application.Abstractions;
using Dyao.Book.Contract;
using Dyao.Book.Core;
using Dyao.Book.Repository.Abstractions;
using Foundation.Core;
using Foundation.Uow;
using Microsoft.Extensions.Logging;

namespace Dyao.Book.Application
{
    /// <summary>
    /// 笔趣阁插件
    /// </summary>
    [Description("BiQuGe")]
    public class BookChapterBiqugePlugins : BaseBookChapterPlugins, IBusinessPlugin<BookChapterPluginsContext>
    {
        /// <summary>
        /// 来源Key
        /// </summary>
        public override string SourceKey { get; set; } = BookSourceType.BiQuGe.ToString();

        private readonly ILogger<BookChapterBiqugePlugins> _logger;

        private readonly IMatchBookChapterSourceSpider _sourceSpider;

        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public BookChapterBiqugePlugins(IBookCatalogueRepository catalogueRepository,
            IMatchBookChapterSourceSpider sourceSpider,
            IUnitOfWorkManager unitOfWorkManager)
            : base(catalogueRepository)
        {
            _sourceSpider = sourceSpider;
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task ExecuteAsync(BookChapterPluginsContext executeContext, Func<BookChapterPluginsContext, CancellationToken, Task> next, CancellationToken cancellationToken)
        {
            await _logger.LogConsumeTimeAsync(async () =>
            {
                if (executeContext == null) throw new ArgumentNullException(nameof(executeContext));

                await SpiderChapterAsync(executeContext.Args, cancellationToken);

                await next(executeContext, cancellationToken);

            }, "ExecuteAsync");
        }

        public override async Task SpiderChapterAsync(BookChapterPluginsArgs args, CancellationToken cancellationToken)
        {
            var bookSource = GetBookSource(args);
            var setting = GetSourceSetting(args);
            await _sourceSpider.CrawBookChapterSourceUrlAsync(bookSource, setting, cancellationToken);
        }
    }
}
